package com.xmlDemo;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.*;


public class SaxUtils {
    /**
     * 生成默认的解析器
     *
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     */
    public static SAXParser createDefaultParser(InputStream stream, DefaultHandler handler) throws ParserConfigurationException, SAXException, IOException {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse(stream, handler);
        return parser;

    }

    public static void readMapper(String fileName) throws FileNotFoundException {
        File file = new File("D:\\workspace\\gitee\\daily_learning_code\\daily_code_java8\\src\\main\\java\\com\\xmlDemo\\test.xml");
        InputStream stream = new FileInputStream(file);
        SAXParser parser = null;


        try {
            parser = createDefaultParser(stream, new DefaultHandler() {
                // 当前元素
                private String currentTag;

                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

                    System.out.println("开始处理元素" + qName);
                    currentTag = qName;

                    int length = attributes.getLength();
                    if (length > 0) {
                        System.out.println(currentTag + "元素中包含属性");
                        for (int i = 0; i < length; i++) {
                            System.out.println(attributes.getQName(i) + "--->" + attributes.getValue(i));
                        }
                    }

                }

                @Override
                public void characters(char[] ch, int start, int length) throws SAXException {
                    String content = new String(ch, start, length);

                    if (content.trim().length() > 0) {
                        System.out.println(currentTag + "元素中的值是" + content);
                    }
                }

                @Override
                public void endDocument() throws SAXException {
                    System.out.println("xml解析完毕");
                }

                @Override
                public void startDocument() throws SAXException {
                    System.out.println("开始读取xml文档");
                }


            });
        } catch (ParserConfigurationException | SAXException | IOException e) {
            throw new RuntimeException("SAX解析器构建失败", e);
        }

        System.out.println(parser);
    }

    public static void main(String[] args) throws FileNotFoundException {
        readMapper("test.xml");

    }
}
